package yt.kpool.view.dialog;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.maning.updatelibrary.InstallUtils;

import java.io.File;

import yt.kpool.R;
import yt.kpool.util.DisplayUtil;
import yt.kpool.view.FlikerProgressBar;


/**
 * Created by Administrator on 2017/11/21.
 */

public class DownLoadDialog extends Dialog {
    private FlikerProgressBar number_progress_bar;
    private Activity context;
    private String content;
    private String url;

    //下载后的APK的命名
    public static final String APK_NAME = "update";
    private static final String TAG = "InstallUtils";

    public DownLoadDialog(Activity context, int theme, String content, String url) {
        super(context, theme);
        this.context = context;
        this.content = content;
        this.url = url;
        this.setCanceledOnTouchOutside(false);
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View view = inflater.inflate(R.layout.dialog_down, null);
        setContentView(view, new ViewGroup.LayoutParams(DisplayUtil.getWidthPixels(context) / 2 + 150,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        number_progress_bar = (FlikerProgressBar) view.findViewById(R.id.number_progress_bar);
//       checkIsAndroidO();
        createview();
    }


    private void createview() {

        new InstallUtils(context, url, APK_NAME, new InstallUtils.DownloadCallBack() {
            @Override
            public void onStart() {

            }

            @Override
            public void onComplete(String path) {
                dismiss();
                Log.i(TAG, "InstallUtils---onComplete:" + path);
                File apkFile = new File(path);
                installApk(context,apkFile);
                /**
                 * 安装APK工具类
                 * @param context       上下文
                 * @param filePath      文件路径
                 * @param authorities   ---------Manifest中配置provider的authorities字段---------
                 * @param callBack      安装界面成功调起的回调
                 */
//                InstallUtils.installAPK(context, path, context.getPackageName() + ".fileProvider", new InstallUtils.InstallCallBack() {
//                    @Override
//                    public void onSuccess() {
//                        Toast.makeText(context, "正在安装程序", Toast.LENGTH_SHORT).show();
//                    }
//
//                    @Override
//                    public void onFail(Exception e) {
//                        Log.d("====", e.toString());
//                        Toast.makeText(context, "安装失败:" + e.toString(), Toast.LENGTH_SHORT).show();
//                    }
//                });

            }

            @Override
            public void onLoading(long total, long current) {
                Log.i(TAG, "InstallUtils----onLoading:-----total:" + total + ",current:" + current);
                number_progress_bar.setProgress((int) (current * 100 / total));
            }


            @Override
            public void onFail(Exception e) {
                dismiss();
                Toast.makeText(context, "下载失败,请从新下载", Toast.LENGTH_SHORT).show();
                Log.i(TAG, "InstallUtils---onFail:" + e.getMessage());
            }

        }).downloadAPK();
    }

    /**
     * 判断是否是8.0,8.0需要处理未知应用来源权限问题,否则直接安装
     */

    public void checkIsAndroidO() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            boolean b = context.getPackageManager().canRequestPackageInstalls();

            if (b) {

                createview();//安装应用的逻辑

            } else {

                //请求安装未知应用来源的权限

                ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, 30);


            }

        } else {

            createview();//安装应用的逻辑

        }

    }


    /**
     * 跳转到设置-允许安装未知来源-页面
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity() {
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     *      * 安装文件
     *      *
     *      * @param mContext
     *      * @param file
     *      
     */
    private void installApk(Context mContext, File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 判断版本大于等于7.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            // 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri data = FileProvider.getUriForFile(mContext, context.getPackageName() + ".fileProvider", file);
            intent.setDataAndType(data, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

}
